package User;

import java.util.Arrays;

public class UserPreference
{
	private Rating[] ratings = new Rating[0];
	
	public void addRating(int itemid, double rating)
	{
		int i = Arrays.binarySearch(ratings, new Rating(itemid, rating));
		
		if (i < 0)
		{
			i = (i * (-1)) - 1;
			
			Rating[] newRating = new Rating[ratings.length + 1];
			System.arraycopy(ratings, 0, newRating, 0, i);
			newRating[i] = new Rating(itemid, rating);
			System.arraycopy(ratings, i, newRating, i + 1, ratings.length - i);
			ratings = newRating;
		}
		else
		{
			ratings[i].setRating(rating);
		}
	}
	
	public double getRating(int itemid)
	{
		try
		{
			return ratings[Arrays.binarySearch(ratings, new Rating(itemid, 0))].getRating();
		}
		catch (Exception e)
		{
			return -1;
		}
	}
	
	public Rating[] getRatings()
	{
		return ratings;
	}
	
	public double[] getRatings(int[] ids)
	{
		double[] result = new double[ids.length];
		for (int i = 0; i < ids.length; i++)
		{
			result[i] = getRating(ids[i]);
		}
		
		return result;
	}
	
	public int[] getItemids()
	{
		int[] result = new int[ratings.length];
		
		for (int i = 0; i < ratings.length; i++)
		{
			result[i] = ratings[i].getId();
		}
		
		return result;
	}
	
	public int[] getSharedIds(User user)
	{
		int[] ids = new int[0];
		
		for (Rating r : ratings)
		{
			if (user.getRating(r.getId()) != -1)
			{
				int[] temp = new int[ids.length + 1];
				System.arraycopy(ids, 0, temp, 0, ids.length);
				temp[ids.length] = r.getId();
				
				ids = new int[temp.length];
				System.arraycopy(temp, 0, ids, 0, temp.length);
			}
		}
		
		return ids;
	}
	
	public int[] getNotShared(int[] items)
	{
		int[] result = new int[0];
		
		for (int i = 0; i < items.length; i++)
		{
			if (Arrays.binarySearch(ratings, new Rating(items[i], 0)) < 0)
			{
				int[] temp = new int[result.length + 1];
				System.arraycopy(result, 0, temp, 0, result.length);
				temp[result.length] = items[i];
				
				result = new int[temp.length];
				System.arraycopy(temp, 0, result, 0, temp.length);
			}
		}
		
		return result;
	}
	
	public String toString()
	{
		String str = "";
		
		for (Rating r : ratings)
		{
			str += r.getId() + ", " + r.getRating() + "\n";
		}
		
		return str;
	}
}
